import React, {memo, useEffect, useRef, useState} from 'react';
import {Redirect} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import {message} from "antd";

import "./login.css";
import request from "../../services/request";
import {checkUser, getUserInformation, saveLanguage} from "./store/actionCreators";
import {GUEST} from "../../common/userRole";
import {saveData} from "../main/store/actionCreators";
import {saveRegistered} from "../register/store/actionCreators";
import {deepClone} from "../../common/utils";

export default memo(function Login() {
  const dispatch = useDispatch();
  const {isUser, data, registered, isCN, userInfo} = useSelector(state => ({
    isUser: state.loginReducer.isUser,
    data: state.dataReducer.data,
    registered: state.registerReducer.registered,
    isCN: state.languageReducer.isCN,
    userInfo: state.loginReducer.info
  }));
  const [isChange, setIsChange] = useState(isCN);
  const userNameId = useRef(),
    passwordId = useRef();
  let username = '',
    password = '';
  let cloneIsChange;

  useEffect(() => {
    //修改谷歌浏览器偏好设置，目的是每次保存文件询问安装位置，
    /*// 文件path一般为C:\Users\Admin\AppData\Local\Google\Chrome\User Data\Default\Preferences
    request({
      url: "/downloadAction/readPreferences",
      method: "get"
    }).then(res => {
    }).catch(err => {
      message.warn(err);
    });*/
    cloneIsChange = deepClone(isChange, cloneIsChange);
    cloneIsChange = /^true$/i.test(localStorage.getItem('isCN')); //将字符串true/false=>布尔类型;
    setIsChange(cloneIsChange);
    dispatch(saveLanguage(cloneIsChange));
  }, []);

  useEffect(() => {
    request({
      url: "/register/check",
      method: "get"
    }).then(res => {
      switch (res.code) {
        case 200:
          break;
        case 500:
          dispatch(saveRegistered(false));
          message.warn("Instrument inactive");
          break;
        default:
          message.warn("error");
          console.log(res);
      }
    }).catch(err => {
      message.warn(err);
    });
  }, []);

  //  切换语言
  function changeLanguage() {
    dispatch(saveLanguage(!isCN));
    //TODO:关掉客户端不清掉缓存，重新刷新进入保留原有中英文的的状态
    localStorage.removeItem('isCN');
    localStorage.setItem('isCN', JSON.stringify(!isCN));
  }

  //  登陆操作
  function login() {
    username = userNameId.current.value;
    password = passwordId.current.value;
    request({
      url: 'user/loginAction',
      data: {
        username,
        password
      },
      method: 'post'
    }).then(res => {
      switch (res.code) {
        case 200:
          /*  if (username === "calculateSuper") {
           cloneSuper = true;
           dispatch(saveCoeSuper(cloneSuper));
           } else {
           cloneSuper=false;
           dispatch(saveCoeSuper(cloneSuper));
           }*/
          isCN
            ? message.info("登陆成功")
            : message.info("Login successful");
          dispatch(checkUser(true));
          localStorage.setItem(username,password)
          dispatch(getUserInformation({...res.data, password: password}));  //  得到的用户信息存入redux
          dispatch(saveData({...data, userName: username}));
          // console.log(userInfo);
          break;
        case 500:
          message.error(res.message);
          break;
        default:
          message.error("error");
          // TODO: 排查错误
          console.log(res);
      }
      username === "Guest" && dispatch(getUserInformation({...res.data, role: GUEST})); //  Guest用户权限
    }).catch(err => message.error(err));
  }

  //  回车控制Sign In
  function inputKeyUp(e) {
    e.key === "Enter" && login();
  }

  //  点击忘记密码提示
  function forgetMessage() {
    isCN
      ? message.info("请联系管理员修改密码")
      : message.info("Contact the platform administrator to change the password");
  }

  return registered
    ? isUser
      ? <Redirect to="/home"/>
      : (
        <div className="login">
          <div onClick={changeLanguage} className="language">{isCN ? "English" : "中文"}</div>
          <div className="title">cqMAN</div>
          <div className="subtitle">{isCN ? "荧光定量PCR云数据处理和分析软件" : "Cloud qPCR Management & Analysis Software"}</div>
          <div className="loginText">{isCN ? "欢 迎" : "Welcome"}</div>
          <div className="loginBox">
            <div>
              <label htmlFor="userName">{isCN ? "用户名" : "User Name"}</label>
              <input onKeyUp={inputKeyUp} ref={userNameId} type="text"/>
            </div>
            <div>
              <label htmlFor="password">{isCN ? "密\xa0\xa0\xa0码" : "Password"}</label>
              <input onKeyUp={inputKeyUp} ref={passwordId} type="password"/>
              <div className="forgetMessage"
                   onClick={forgetMessage}
              >{isCN ? "忘记密码?" : "Forgot Password?"}</div>
            </div>
            <div onClick={login}>{isCN ? "登 陆" : "Sign In"}</div>
          </div>
        </div>
      )
    : <Redirect to="/register"/>;
});


